package com.cleaner.base.ktx


import android.view.View
import androidx.core.view.ViewCompat
import kotlinx.coroutines.*

/**
 * 当view从视图中分离时，取消协程
 */
class AutoDisposable(private val view: View, private val wrapped: Job) : Job by wrapped,
    View.OnAttachStateChangeListener {
    override fun onViewAttachedToWindow(v: View?) = Unit

    override fun onViewDetachedFromWindow(v: View?) {
        cancel()
        view.removeOnAttachStateChangeListener(this)
    }

    init {
        // 若view已经添加到窗口上，则添加监听
        if (ViewCompat.isAttachedToWindow(view)) {
            view.addOnAttachStateChangeListener(this)
        } else {
            cancel()
        }

        // 协程完成（包括取消协程）时回调
        invokeOnCompletion {
            view.removeOnAttachStateChangeListener(this)
        }
    }
}

fun Job.asAutoDisposable(view: View) = AutoDisposable(view, this)

fun View.onDelayClick(delay: Long = 500L, onClick: (View) -> Unit) {
    var last = 0L
    setOnClickListener {
        val now = System.currentTimeMillis()
        if (now - last <= delay) return@setOnClickListener
        last = now
        onClick(it)
    }
}

@OptIn(DelicateCoroutinesApi::class)
fun View.onLaunchClick(onClick: suspend CoroutineScope.(View) -> Unit) {
    onDelayClick {
        GlobalScope.launch(Dispatchers.Main) { onClick(this@onLaunchClick) }.asAutoDisposable(this)
    }
}